// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
//
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.core.scripts;

import java.util.List;

import org.dengues.core.IScriptsPluginService;
import org.dengues.model.DenguesModelManager;
import org.dengues.model.database.DBColumn;
import org.dengues.model.database.DBTable;
import org.dengues.model.database.DatabaseDiagram;
import org.dengues.model.database.DiagramChild;
import org.dengues.model.database.EMFDataType;
import org.dengues.model.database.ForeignKey;
import org.eclipse.emf.common.util.EList;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf Qiang.Zhang.Adolf@gmail.com 2008-6-11 qiang.zhang $
 * 
 */
public class ScriptResultBean {

    private static int len = 9;

    private String result;

    private ScriptDataBean dataBean;

    private String trimName;

    /**
     * Qiang.Zhang.Adolf@gmail.com ScriptResultBean constructor comment.
     * 
     * @param dataBean
     */
    public ScriptResultBean(ScriptDataBean dataBean) {
        this.dataBean = dataBean;
    }

    /**
     * Getter for result.
     * 
     * @return the result
     */
    public String getResult() {
        return this.result;
    }

    /**
     * Sets the result.
     * 
     * @param result the result to set
     */
    public void setResult(String result) {
        this.result = result;
        this.trimName = getTrimLinkName(this.result);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getTrimLinkName".
     */
    public static String getTrimLinkName(String result) {
        String trimName = null;
        if (result == null) {
            return null;
        } else if (result.length() > len) {
            trimName = result.substring(0, len) + "...";
        } else {
            trimName = result;
        }
        return trimName;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "link".
     */
    public void link() {
        DBColumn source = null;
        DBColumn target = null;
        DBColumn data = dataBean.getData();
        DBTable dbtable = data.getTable();
        boolean isSource = true;
        if (IScriptsPluginService.MATATPYE_INPUT.equals(dbtable.getMetaType())) {
            source = data;
            EList<ForeignKey> outputs = source.getOutputs();
            for (ForeignKey foreignKey : outputs) {
                foreignKey.getTarget().getInputs().remove(foreignKey);
            }
            outputs.clear();
        } else {
            target = data;
            EList<ForeignKey> inputs = target.getInputs();
            for (ForeignKey foreignKey : inputs) {
                foreignKey.getSource().getOutputs().remove(foreignKey);
            }
            inputs.clear();
            isSource = false;
        }
        DatabaseDiagram dbDiagram = dbtable.getDbDiagram();
        for (DiagramChild child : dbDiagram.getDbChildren()) {
            if (child instanceof DBTable) {
                DBTable table = (DBTable) child;
                String conName = table.getName();
                EList<DBColumn> columns = table.getColumns();
                if (IScriptsPluginService.MATATPYE_INPUT.equals(table.getMetaType())) {
                    for (DBColumn col : columns) {
                        String name = conName + "." + col.getName();
                        if (result.contains(name)) {
                            if (!isSource) {
                                source = col;
                            } else {
                                target = col;
                            }
                            link(source, target);
                        }
                    }
                }
            }
        }
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "link".
     * 
     * @param source
     * @param target
     */
    public void link(DBColumn source, DBColumn target) {
        // if (canExecute(source, target)) {
        ForeignKey key = DenguesModelManager.getDatabaseFactory().createForeignKey();
        key.setSource(source);
        key.setTarget(target);
        source.getOutputs().add(key);
        target.getInputs().add(key);
        // }
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "canExecute".
     * 
     * @param source
     * @param target
     * @return
     */
    public static boolean canExecute(DBColumn source, DBColumn target) {
        if (source == null || target == null) {
            return false;
        }
        if (source.equals(target)) {
            return false;
        }
        EList<ForeignKey> outputs = source.getOutputs();
        for (ForeignKey foreignKey : outputs) {
            if (foreignKey.getTarget().equals(target) || foreignKey.getTarget().equals(source)) {
                return false;
            }
        }
        EList<ForeignKey> inupts = source.getInputs();
        for (ForeignKey foreignKey : inupts) {
            if (foreignKey.getSource().equals(source) || foreignKey.getSource().equals(target)) {
                return false;
            }
        }
        DatabaseDiagram dbDiagram = source.getTable().getDbDiagram();
        if (dbDiagram.getEmfType().equals(EMFDataType.MAPPER)) {
            return !IScriptsPluginService.MATATPYE_OUTPUT.equals(source.getTable().getMetaType());
        }
        return true;
    }

    /**
     * Getter for trimName.
     * 
     * @return the trimName
     */
    public String getTrimName() {
        return this.trimName;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "linkAll".
     * 
     * @param linkCols
     */
    public static void linkAll(List<DBColumn> linkCols) {
        for (DBColumn column : linkCols) {
            ScriptDataBean bean = new ScriptDataBean();
            bean.setData(column);
            ScriptResultBean resultBean = new ScriptResultBean(bean);
            resultBean.result = column.getLinkName();
            resultBean.link();
        }
    }
}
